<?php

namespace app\mall\middleware;

use app\mall\exceptions\ApiException;
use app\mall\middleware\auth\Auth;
use think\Request;

class ApiAuth
{

    /**
     * @param Request $request
     * @param \Closure $next
     * @return mixed
     * @throws \Exception
     */
    public function handle($request, \Closure $next)
    {
        $uid = 1;
        if (!$uid) {
            $auth = new Auth();
            if ($auth->guest() && !$this->shouldPassThrough($request)) {
                ApiException::throws(ApiException::$needLogin);
            }
            $uid = $auth->getUid();
        }
        $get = $request->get();
        $get['__UID__'] = $uid;
        $request->withGet($get);
        return $next($request);
    }

    /**
     * 白名单
     * @param Request $request
     * @return bool
     */
    protected function shouldPassThrough(Request $request)
    {
        $excepts = [
            'api/auth/login',
            'api/auth/phoneCode',
            'api/auth/phoneCodeLogin',
            'api/auth/weixin',
            'api/auth/refreshToken',
        ];
        $pathInfo = $request->pathinfo();
        if ($pathInfo == 'favicon.ico') {
            return true;
        }
        foreach ($excepts as $except) {
            if ($pathInfo == $except) {
                return true;
            }
        }
        return false;
    }
}
